/*
 * RunPipeline.java
 *
 * Created on September 2, 2006, 1:22 PM
 *
 * (C) 2006 R. Alexander Milowski
 */

package com.smallx.xproc.tools;

import com.smallx.xproc.compiler.StreamingCompiler;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import org.infoset.component.Component;
import org.infoset.component.ComponentContextBase;
import org.infoset.component.ComponentDefinition;
import org.infoset.xml.Document;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.Name;
import org.infoset.xml.XMLException;
import org.infoset.xml.util.WriterItemDestination;
import org.infoset.xproc.Pipeline;

/**
 *
 * @author alex
 */
public class StreamPipeline extends CommandLine {
   
   /** Creates a new instance of RunPipeline */
   public StreamPipeline() {
   }
   
   protected void usage() {
      System.err.println(this.getClass().getName()+" pipeline input-document");
   }
   
   protected void setup() {
      setMinimumArguments(2);
   }
   
   protected ItemDestination getOutput() 
      throws IOException,XMLException
   {
      Writer out = new OutputStreamWriter(System.out,"UTF-8");
      return new WriterItemDestination(out,"UTF-8");      
   }
   
   protected int runProgram() {
      String [] args = getArguments();
      try {
         URI pipeLocation = toURI(args[0]);
         URI inputDocument = toURI(args[1]);
         StreamingCompiler compiler = new StreamingCompiler();
         Document pipeDocument = compiler.getDocumentLoader().load(pipeLocation);
         Pipeline pipe = compiler.compile(pipeDocument);
         
         ComponentDefinition def = pipe.getDefinition();
         Component pipeComponent = def.newInstance();
         Name inputName = def.getInputs().iterator().next();
         Name outputName = def.getOutputs().iterator().next();

         ComponentContextBase context = new ComponentContextBase(pipeLocation,pipeDocument.getDocumentElement().getNamespaceScope());
         
         pipeComponent.init(context);
         pipeComponent.bindOutputPort(outputName,getOutput());
         
         pipeComponent.onStart();
         compiler.getDocumentLoader().generate(inputDocument,pipeComponent.getInputPort(inputName));
         pipeComponent.onEnd();
         
         return 0;
      } catch (XMLException ex) {
         ex.printStackTrace();
      } catch (IOException ex) {
         ex.printStackTrace();
      } catch (URISyntaxException ex) {
         ex.printStackTrace();
      }
      return 1;
   }
   
   public static void main(String [] args) {
      StreamPipeline cmd = new StreamPipeline();
      if (cmd.parseArguments(args)) {
         cmd.run();
         System.exit(cmd.getStatusCode());
      } else {
         System.exit(1);
      }
   }
   
}
